<?
require_once dirname(__FILE__).'/ImportBase.php';
class ImportStatistic extends ImportBase{

	private static $instance;

    public static function &get_instance() {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

	private function get_bbs_forum_list(){
		$sql='select * from forums';
		$stmt=$this->bbs_pdo->prepare($sql);
		$stmt->execute();
		return $stmt->fetchAll();
	}

	public function stat_one_forum($forum_id){

		$sql='select count(\'x\') from threads where forum_id=?';
		$stmt=$this->bbs_pdo->prepare($sql);
		$stmt->execute(array($forum_id));
		$thread_count=$stmt->fetchColumn();

		$sql='select count(\'x\') from threads where digest=1 and forum_id=?';
		$stmt=$this->bbs_pdo->prepare($sql);
		$stmt->execute(array($forum_id));
		$thread_digest_count=$stmt->fetchColumn();

		$sql='select count(\'x\') from replies as a left join threads as b on a.thread_id=b.id where b.forum_id=?';
		$stmt=$this->bbs_pdo->prepare($sql);
		$stmt->execute(array($forum_id));
		$post_count=$stmt->fetchColumn();

		$lastpost='';
		$sql='select * from threads where forum_id=? order by updated desc limit 1';
		$stmt=$this->bbs_pdo->prepare($sql);
		$stmt->execute(array($forum_id));
		$thread_info=$stmt->fetch();
		if($thread_info){
			$sql="select username from users where id=".$thread_info['author_id'];
			$stmt=$this->bbs_pdo->prepare($sql);
			$stmt->execute();
			$author_name=$stmt->fetchColumn();
			$lastpost=$thread_info['id']."\t".htmlspecialchars($thread_info['title'])."\t".$thread_info['updated']."\t".$author_name;
		}


		$sql="update forums_ext set threads=?,digest_threads=?,posts=?,lastpost=? where id=?";
		$stmt=$this->bbs_pdo->prepare($sql);
		$stmt->execute(array($thread_count,$thread_digest_count,$post_count,$lastpost,$forum_id));
	}


	public function stat_forum_ext(){
		$forum_list=$this->get_bbs_forum_list();
		if(!$forum_list)return false;
		foreach($forum_list as $v){
			$this->stat_one_forum($v['id']);
		}
	}

}

ImportStatistic::get_instance()->stat_forum_ext();